//
//  XMWeiboAccount.m
//  XMWeibo
//
//  Created by chi on 14-8-22.
//  Copyright (c) 2014年 xiaoming. All rights reserved.
//

#import "XMWeiboAccount.h"

static XMWeiboAccount *sharedAccount = nil;

@implementation XMWeiboAccount

- (NSString *)description
{
   return [NSString stringWithFormat:@"XMWeiboAccount <%p> {\naccess_token=%@\nuid=%lld\nexpiresDateTime=%@\n}", self, self.access_token, self.uid, self.expiresDateTime];
}

+ (NSString*)savePath
{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
   return [path stringByAppendingPathComponent:@"user.dat"];
}

+ (void)loadAccount
{
    [NSKeyedUnarchiver unarchiveObjectWithFile:[self savePath]];
}

+ (void)saveAccount
{
    NSString *path = [self savePath];
    
    [NSKeyedArchiver archiveRootObject:[XMWeiboAccount account] toFile:path];
}

- (BOOL)isExpireAccount
{
    NSDate *nowDate = [NSDate date];
    
    if ([nowDate compare:self.expiresDateTime] == NSOrderedAscending) {
        return NO;
    }
    
    return YES;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        self.access_token = [aDecoder decodeObjectForKey:@"access_token"];
        self.uid = [[aDecoder decodeObjectForKey:@"uid"]longLongValue];
        self.expiresDateTime = [aDecoder decodeObjectForKey:@"expiresDateTime"];
    }
    
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.access_token forKey:@"access_token"];
    [aCoder encodeObject:@(self.uid) forKey:@"uid"];
    [aCoder encodeObject:self.expiresDateTime forKey:@"expiresDateTime"];
}

+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedAccount = [super allocWithZone:zone];
    });
    
    return sharedAccount;
}


+ (instancetype)weiboAccountWithDictionary:(NSDictionary *)dict
{
    XMWeiboAccount *acc = [[XMWeiboAccount alloc]init];
    
    acc.access_token = dict[@"access_token"];
    acc.uid = [dict[@"uid"]longLongValue];
    
    //过期时间
    long long s = [dict[@"expires_in"]longLongValue];
    
    NSDate *nowDate = [NSDate date];
    acc.expiresDateTime = [nowDate dateByAddingTimeInterval:s];
    
    return acc;
}

+ (void)resetAccount
{
    sharedAccount.access_token = nil;
    sharedAccount.expiresDateTime = nil;
    sharedAccount.uid = nil;
}

+ (instancetype)account
{
    return sharedAccount;
}

@end
